package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;

    // 用户下单
    @Override
    public void submit(Order order) {
        // 1.获取登录人user对象
        User user = UserHolder.get();
        if (user == null) {
            throw new CustomException("登录人为空不能下单");
        }
        // 2.根据id查询收货地址
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址为空不能下单");
        }
        // 3.获取购物车列表 (查询购物车)
        List<Cart> cartList = cartService.list();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车为空不能下单");
        }
        // 通过mp生成订单id 雪花
        long orderId = IdWorker.getId();
        // 订单金额
        BigDecimal amount = new BigDecimal(0);

        // 4.遍历购物车
        for (Cart cart : cartList) {
            // 封装订单明细
            OrderDetail orderDetail = new OrderDetail();
            // orderDetail.setId(id);
            orderDetail.setName(cart.getName()); // 菜品或套餐名称
            orderDetail.setOrderId(orderId); // 订单id
            orderDetail.setDishId(cart.getDishId()); // 菜品id
            orderDetail.setSetmealId(cart.getSetmealId());// 套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());// 口味
            orderDetail.setNumber(cart.getNumber()); // 数量
            orderDetail.setAmount(cart.getAmount()); // 金额
            orderDetail.setImage(cart.getImage()); // 图片
            // mapper保存
            orderDetailMapper.insert(orderDetail);
            // 累加
            //amount=amount+(cart.getAmount()*cart.getNumber());
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        // 5.保存订单
        // 5-1 封装
        order.setId(orderId); // 订单id
        order.setNumber(String.valueOf(orderId)); // 订单号
        order.setStatus(1); // 待付款
        order.setUserId(user.getId()); // 下单用户id
        order.setOrderTime(new Date()); // 下单时间
        order.setCheckoutTime(new Date()); // 结账时间
        order.setAmount(amount); // 实收金额
        order.setUserName(user.getName()); // 下单用户名称
        order.setPhone(address.getPhone()); // 收货人手机号
        order.setAddress(address.getDetail()); // 收货人地址
        order.setConsignee(address.getConsignee()); // 收货人姓名
        // 5-2 mapper保存
        orderMapper.insert(order);

        // 6.清空购物车
        cartService.clean();

    }


    //订单明细列表查询
    @Override
    public Page<Order> findByOrder(Integer pageNum, Integer pageSize, String number, Date beginTime, Date endTime) {
       //根据订单号查询订单列表
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.between(beginTime!=null,Order::getCheckoutTime,beginTime,endTime ).like(number !=null,Order::getNumber,number);

      /*  两种都可以
        qw.like(StrUtil.isNotBlank(number),Order::getNumber,number);
        qw.gt(beginTime != null ,Order::getCheckoutTime,beginTime);
        qw.lt(endTime != null,Order::getCheckoutTime,endTime);*/
        //开启分页
        Page<Order> page = new Page<>(pageNum, pageSize);
        //分页查询
         page = orderMapper.selectPage(page, qw);
        return page;
    }


    //历史订单
    @Override
    public Page<Order> findUserPage(Integer pageNum, Integer pageSize) {
       //构建条件,根据用户id查询订单 并且根据下单时间降序
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(Order::getUserId,UserHolder.get().getId()).orderByDesc(Order::getOrderTime);

        //开启分页
        Page<Order> page = new Page<>(pageNum, pageSize);
        //分页查询
        Page<Order> page1 = orderMapper.selectPage(page, qw);
        //遍历分页查询结果(通过page1.getRecords()方法拿到订单集合)
        List<Order> orderList = page1.getRecords();
        //遍历订单集合
        for (Order order : orderList) {
            //构建条件 通过订单表里的id 查询 订单明细表的OrderId(主外键关系)
            LambdaQueryWrapper<OrderDetail> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(qw2);
            //把订单明细设置到订单表里
            order.setOrderDetails(orderDetails);

        }

        return page1;
    }
}